package com.srwl.mytx.widget;


import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.fragment.BaseFragment;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.R;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class WithdrawDialogFragment extends BaseFragment implements View.OnClickListener {
    private static String TAG = "WithdrawDialogFragment";
    private Button mBtnPutMoney;
    private String mMoneyAmount;
    private EditText mEtMoneyAmount, et_aliAccount;
    private User loginUserInfo;
    private OnFragmentInteractionListener mListener;

    private ProgressBar progressBar;

    public static WithdrawDialogFragment newInstance() {
        WithdrawDialogFragment fragment = new WithdrawDialogFragment();

        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, R.style.RechargeDialogStyle);
        loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_withdraw, container, false);
        initViewsAndEvents(view);
        return view;
    }


    protected void initViewsAndEvents(View view) {
        progressBar = view.findViewById(R.id.progress_bar);
        et_aliAccount = view.findViewById(R.id.et_ali_account);
        if (loginUserInfo.getAliAccount() != null) {
            et_aliAccount.setText(loginUserInfo.getAliAccount());
        }
        mBtnPutMoney = view.findViewById(R.id.btn_transfer);
        mBtnPutMoney.setOnClickListener(this);
        enableButton(false);
        mEtMoneyAmount = view.findViewById(R.id.et_transfer_money);
        MoneyInputCheck inputCheck = new MoneyInputCheck(getActivity(), 1d, loginUserInfo.getBalance() - loginUserInfo.getDeposit(), new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
                mEtMoneyAmount.setError(message);
            }

            @Override
            public void waitInput() {
                enableButton(false);
            }

            @Override
            public void inputRight() {
                enableButton(true);
            }
        });

        mEtMoneyAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                inputCheck.afterTextChanged(s);
            }
        });


    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.btn_transfer) {
            if (ClickUtil.isFastClick()) return;
            hideSoftKeyboard();
            String aliAccount = et_aliAccount.getText().toString();
            mMoneyAmount = mEtMoneyAmount.getText().toString().trim();
            if (TextUtils.isEmpty(et_aliAccount.getText().toString())) {

                //showToast(mBtnPutMoney, "请输入支付宝账户");
                Toast.makeText(getContext(), "请输入支付宝账户", Toast.LENGTH_LONG).show();
                return;
            }
            new PayUtils(Double.valueOf(mMoneyAmount), getActivity(), new PayUtils.InteractionListener() {
                @Override
                public void onPrepareComplete(String payPassword) {
                    withdraw(payPassword, aliAccount);
                }
            });
        }
    }

    private void withdraw(String payPassword, String aliAccount) {
        if (!Helper.getInstance().isNetworkConnected()){
            Toast.makeText(getActivity(), getActivity().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> info = new HashMap<>();
        info.put("amount", mMoneyAmount);
        info.put("aliAccount", aliAccount);
        info.put("payPassword", payPassword);
        progressBar.setVisibility(View.VISIBLE);
        //请求服务端获取支付url
        RetrofitManager.getInstance().createRequest(AliService.class)
                .transfer(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, final Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "申请提现出错 " + response.message());
                            showToast(mBtnPutMoney, "系统错误");
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "申请提现出错 " + result.getMsg());
                            if (result.getStatus() == Constant.TOKEN_INVALID) {
                                showToast(getString(R.string.login_expire));
                            } else if (result.getStatus() == Constant.PAY_PASSWORD_ERROR) {
                                showToast(mBtnPutMoney, "支付密码错误");
                            } else if (result.getStatus() == Constant.BALANCE_NOT_ENOUGH) {
                                showToast(mBtnPutMoney, "账户余额不足");
                            } else {
                                showToast(mBtnPutMoney, "系统错误");
                            }
                            return;
                        }
                        Log.d(TAG, "申请提现完成" + result.getMsg());
                        Object data = result.getData();
                        if (data == null) return;
                        double balance = ((BigDecimal) data).doubleValue();
                        UserProfileManager.getInstance().setUserBalance(balance);
                        if (mListener != null) {
                            mListener.onWithdrawSuccess(balance);
                        }
                        dismiss();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        t.printStackTrace();
                        Log.e(TAG, "申请提现出错 " + t.getMessage());
                        showToast(mBtnPutMoney, "系统繁忙");
                    }
                });
    }


    private void enableButton(boolean enable) {
        mBtnPutMoney.setEnabled(enable);
    }


    @Override
    public void onResume() {
        super.onResume();
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, screenHeight / 2);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);

        dialog.setCanceledOnTouchOutside(true);
        // 设置宽度为屏宽、靠近屏幕底部。
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wlp.height = screenHeight / 2;
        window.setAttributes(wlp);
        return dialog;

    }


    public void setOnFragmentInteractionListener(OnFragmentInteractionListener listener) {
        this.mListener = listener;
    }

    public interface OnFragmentInteractionListener {
        void onWithdrawSuccess(double balance);


    }

}
